<template>
  <div class="creat-post-page">
    <h4>新建文章</h4>
    <uploader
      :before-upload="uploadCheck"
      @file-iploaded="handleFileUploaded"
      :uploaded="uploadedData"
      action="/upload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
    >
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <span class="sr-only"></span>
          </div>
          <h2>正在上传</h2>
        </div>
      </template>
      <template #uploaded="dataProps">
        <div class="uploaded-area">
          <img :src="dataProps.uploadedData.data.url">
          <h3>点击重新上传</h3>
        </div>
      </template>
    </uploader>
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">文章标题:</label>
        <validate-input
          :rules="titleRules" v-model="titleVal"
          placeholder="请输入文章标题"
          type="text"
        ></validate-input>
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情:</label>
        <validate-input
          :rules="contentRules" v-model="contentVal"
          placeholder="请输入文章详情"
          type="text"
          tag="textarea"
          rows="10"
        ></validate-input>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">发表文章</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import ValidateForm from '@/components/ValidateForm.vue'
import ValidateInput, { RulesProp } from '@/components/ValidateInput.vue'
import { GlobalDataProps, ResponseType, ImageProps, PostProps, ListData } from '@/store'
import { defineComponent, ref, onMounted, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import Uploader from '@/views/Uploader.vue'
import { beforeUploadCheck } from '@/selfFunction/helper'
import createMessage from '@/selfFunction/createMessage'

export default defineComponent({
  name: 'CreatePost',
  components: {
    Uploader,
    ValidateInput,
    ValidateForm
  },
  setup () {
    const uploadedData = ref()
    const titleVal = ref('')
    const router = useRouter()
    const route = useRoute()
    const isEditMode = !!route.query.id
    const store = useStore<GlobalDataProps>()
    let imageId = ''
    const titleRules: RulesProp = [
      {
        type: 'required',
        message: '文章标题不能为空'
      }
    ]
    const contentVal = ref('')
    const contentRules: RulesProp = [
      {
        type: 'required',
        message: '文章详情不能为空'
      }
    ]
    onMounted(() => {
      if (isEditMode) {
        store.dispatch('fetchPost', route.query.id).then((rawData: ResponseType<PostProps>) => {
          const currentPost = rawData.data
          if (currentPost.image) {
            uploadedData.value = { data: currentPost.image }
          }
          titleVal.value = currentPost.title
          contentVal.value = currentPost.content || ''
        })
      }
    })
    const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id
      }
      console.log('uploadedData:', uploadedData)
    }
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const {
          columnId,
          column
        } = store.state.user
        // console.log(1)
        // console.log(columnId)
        if (column) {
          const newPost: PostProps = {
            author: store.state.user.nickName,
            avatar: {
              _id: '',
              url: 'http://vue-maker.oss-cn-hangzhou.aliyuncs.com/vue-marker/5f3e3a17c305b1070f455202.jpg'
            },
            title: titleVal.value,
            createdAt: new Date().toTimeString(),
            description: contentVal.value,
            __v: 0,
            key: 4,
            featured: true,
            columnId,
            column
          }
          if (imageId) {
            newPost.image = imageId
          }
          const actionName = isEditMode ? 'updatePost' : 'createPost'
          const sendData = isEditMode ? {
            id: route.query.id,
            payload: newPost
          } : newPost
          store.dispatch(actionName, sendData).then(() => {
            createMessage('发表成功 2秒后跳转到文章', 'success', 2000)
            setTimeout(() => {
              router.push({
                name: 'column',
                params: { id: 4 }
              })
            }, 2000)
          })
        }
      }
    }
    const uploadCheck = (file: File) => {
      const result = beforeUploadCheck(file, {
        format: ['image/jpeg', 'image/png'],
        size: 1
      })
      const {
        passed,
        error
      } = result
      if (error === 'format') {
        createMessage('上传图片只能是 JPG/PNG 格式', 'error')
      }
      if (error === 'size') {
        createMessage('上传图片大小不能超过 1Mb', 'error')
      }
      return passed
    }
    // 返回用户输入的信息
    const postData: ListData = reactive({
      author: store.state.user.nickName,
      title: titleVal,
      description: contentVal,
      _id: '1'
    })
    return {
      titleVal,
      titleRules,
      contentVal,
      contentRules,
      uploadedData,
      isEditMode,
      onFormSubmit,
      uploadCheck,
      handleFileUploaded
    }
  }
})
</script>

<style scoped>
.creat-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
}

.creat-post-page img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
